

function say() {
    alert("LC:227. 基本计算器 II");
}
say();

/**
 * @param {string} s
 * @return {number}
 */
var calculate = function(s) {
  //4:43-5:15
  s = s.split(' ').join('')

  var numStack = [], opStack = []
  for(var i = 0; i < s.length; i++){
    var item = s.charAt(i)
    if(isNum(item)){
      var gap = 1
      while(i + gap < s.length && isNum(s.charAt(i + gap))){
        gap++
      }
      let numStr = s.slice(i, i + gap)
      numStack.push(parseInt(numStr))
      i = i + gap - 1
    }else {
      if(opStack.length == 0){
        opStack.push(item)
      }else {
        //比较栈顶运算符
        dealSymbol(item, opStack, numStack)
      }
    }
  }

  var yunSuan = opStack.pop()
  while(yunSuan){
    myCal(yunSuan, numStack)
    yunSuan = opStack.pop()
  }
  return numStack.pop()
};

function dealSymbol(current, opStack, numStack){
  var top = opStack[opStack.length - 1]
  let dic = {
    '+':1,
    '-':1,
    '*':2,
    '/':2,
  }
  var oldLevel = dic[top]
  var currentLevel = dic[current]

  if(oldLevel < currentLevel){

  }else { //循环计算old
    var yunSuan = opStack.pop()

    while(yunSuan) {
      if(dic[yunSuan] < currentLevel){
        opStack.push(yunSuan)
        break
      }
      myCal(yunSuan, numStack)
      yunSuan = opStack.pop()
    }
  }
  opStack.push(current)
}

function myCal(yunSuan,numStack){

  var lastNum = numStack.pop()
  var preNum = numStack.pop()
  
  preNum = typeof(preNum) == 'undefined' ? 0 : preNum

  if(yunSuan == '/'){
    numStack.push(Math.floor(preNum / lastNum))
  }else if(yunSuan == '*'){
    numStack.push(preNum * lastNum)
  }else if(yunSuan == '-'){
    numStack.push(preNum - lastNum)
  }else {
    numStack.push(preNum + lastNum)
  }
}

function isNum(string){
  let code = string.charCodeAt(0)
  if(code >= '0'.charCodeAt(0) && code <= '9'.charCodeAt(0)){
    return true
  }else {
    return false
  }
}
